package com.deshan.websys.api.controller;

import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.deshan.websys.api.utils.CommonResult;
import com.deshan.websys.code.model.Goods;
import com.deshan.websys.code.model.vo.GoodsVO;
import com.deshan.websys.code.service.GoodsService;

import cn.hutool.core.util.ArrayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.sf.cglib.beans.BeanCopier;

@Api(tags = "产品后台管理")
@RestController
@RequestMapping("/manage/goods")
@AllArgsConstructor
public class GoodsController {

	private final GoodsService goodsService;

	private final static BeanCopier BEAN_COPIER = BeanCopier.create(GoodsVO.class, Goods.class, false);

	@ApiOperation("创建和修改")
	@PostMapping("/save")
	public CommonResult saveGoods(@RequestBody GoodsVO goodsVO) {
		Goods goods = new Goods();
		BEAN_COPIER.copy(goodsVO, goods, null);
		goods.setPageType(3);
		return goodsService.saveOrUpdate(goods) ? CommonResult.success() : CommonResult.failed("保存失败");
	}

	@ApiOperation("删除")
	@DeleteMapping("/delete/{id}")
	public CommonResult deleteGoods(@PathVariable("id") String id) {
		return goodsService.removeById(id) ? CommonResult.success() : CommonResult.failed("删除失败");
	}

	@ApiOperation("批量删除")
	@DeleteMapping("/delete/{ids}")
	public CommonResult batchDeleteGoods(@PathVariable("ids") String[] ids) {
		if (ArrayUtil.isNotEmpty(ids)) {
			for (String id : ids) {
				deleteGoods(id);
			}
		}
		return CommonResult.success();
	}

	@ApiOperation("根据ID查询产品")
	@GetMapping("/getone")
	public CommonResult<Goods> getGoods(@RequestParam("id") String id) {
		return CommonResult.success(goodsService.getById(id));
	}

	@ApiOperation("查询当前法人下的所有产品")
	@GetMapping("/list/{legalCode}")
	public CommonResult<List<Goods>> listGoods(@PathVariable("legalCode") String legalCode) {
		return CommonResult
				.success(goodsService.list(Wrappers.lambdaQuery(Goods.class).eq(Goods::getLegalCode, legalCode)));
	}
}
